<script lang="ts">
    import { onDestroy, untrack } from "svelte";
    import { useClassList } from "../utils/useClassList";
    import type { SideBySideProps } from "./SideBySide";
    import { useStyle } from "../utils/useStyle";

    const props: SideBySideProps = $props();
    const classList = $derived(useClassList(props, "cm-side-by-side"));
    let split = $state(props.split ?? 50);
    let wrap: any;
    const store = $state({
        dragging: false,
        x: NaN,
        y: NaN,
        deltaX: 0,
        deltaY: 0,
    });

    $effect(() => {
        const wrapRect = wrap.getBoundingClientRect();
        let w = untrack(() => split);

        w = w + (store.deltaX / wrapRect.width) * 100;
        w = Math.min(w, 100);
        w = Math.max(w, 0);
        split = w;
    });

    const onDragStart = (e: any) => {
        if (typeof e.button === "number" && e.button !== 0) return false;

        store.dragging = true;
        const x = e.clientX;
        const y = e.clientY;
        store.x = x;
        store.y = y;

        document.addEventListener("mousemove", onDragMove, false);
        document.addEventListener("mouseup", onDragEnd, false);
    };

    const onDragMove = (e: any) => {
        const deltaX = e.clientX - store.x;
        const deltaY = e.clientY - store.y;
        store.x = e.clientX;
        store.y = e.clientY;
        store.deltaX = deltaX;
        store.deltaY = deltaY;
    };
    const onDragEnd = (e: any) => {
        store.dragging = false;
        document.removeEventListener("mousemove", onDragMove);
        document.removeEventListener("mouseup", onDragEnd);
        store.deltaX = 0;
        store.deltaY = 0;
    };

    const leftStyle = $derived(
        useStyle(
            {},
            {
                "clip-path": `inset(0 ${100 - split}% 0 0)`,
            },
        ),
    );

    const handlerStyle = $derived(
        useStyle(
            {},
            {
                left: `${split}%`,
            },
        ),
    );

    onDestroy(() => {
        document.removeEventListener("mousemove", onDragMove);
        document.removeEventListener("mouseup", onDragEnd);
    });
</script>

<div class={classList} style={props.style} bind:this={wrap}>
    <div class="cm-sbs-right-panel">
        {@render props.right?.()}
    </div>
    <div class="cm-sbs-left-panel" style={leftStyle}>
        {@render props.left?.()}
    </div>
    <!-- svelte-ignore a11y_no_static_element_interactions -->
    <div class="cm-sbs-handler" style={handlerStyle} onmousedown={onDragStart}>
        <div class="cm-sbs-track">
            <div class="cm-sbs-line"></div>
            <div class="cm-sbs-line"></div>
            <div class="cm-sbs-line"></div>
        </div>
    </div>
</div>
